﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Script.Serialization;
using System.Net;

namespace MabiCommerce
{
    class Web
    {
        static JavaScriptSerializer json = new JavaScriptSerializer();
        /// <summary>
        /// Retrives the profit information for the specified town and server
        /// </summary>
        /// <param name="serverName">Either the server name or a string of the format IP_Port</param>
        /// <param name="townName">The town name</param>
        /// <returns>A dictonary where keys are item names, and values are a (dictionary where keys are town names and values are the profit for that town)</returns>
        public static Dictionary<string, Dictionary<string, int>> GetFromServer(string serverName, string townName)
        {
            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(Properties.Settings.Default.serverURL + string.Format("{0}/{1}/json/", serverName, townName));
            req.Method = "GET";
            req.UserAgent = "Mozilla/5.0 (Windows; U; MSIE 9.0; WIndows NT 9.0; en-US))";
            HttpWebResponse resp = null;
            try
            {
                resp = (HttpWebResponse)req.GetResponse();
            }
            catch (WebException ex)
            {
                if (ex.Status != WebExceptionStatus.ProtocolError)
                {
                    //System.Windows.Forms.MessageBox.Show(ex.Status.ToString());
                    return null;
                }
                resp = (HttpWebResponse)ex.Response; //Because @#$% logic.
            }
            string respStr;
            using (System.IO.StreamReader r = new System.IO.StreamReader(resp.GetResponseStream()))
            {
                respStr = r.ReadToEnd();
            }
            if (resp.StatusCode == HttpStatusCode.Conflict)
            {
                //System.Windows.Forms.MessageBox.Show(respStr);
                return null;
            }
            else if (resp.StatusCode != HttpStatusCode.OK)
            {
                //System.Windows.Forms.MessageBox.Show((int)resp.StatusCode + " - " + resp.StatusDescription);
                return null;
            }
            return json.Deserialize<Dictionary<string, Dictionary<string, int>>>(respStr);
        }

        public static Dictionary<string, Dictionary<string, int>> GetFromIP(string townName)
        {
            List<System.Diagnostics.Process> Processes = System.Diagnostics.Process.GetProcessesByName("client").ToList();
            Processes = Processes.Where(new Func<System.Diagnostics.Process, bool>((p) => { return p.MainWindowTitle.Equals("Mabinogi"); })).ToList();
            if (Processes.Count == 0)
            {
                System.Windows.Forms.MessageBox.Show("Cannot find Mabinogi! Is it running?");
                return null;
            }

            List<IPEndPoint> PotentialIPs = new List<IPEndPoint>();

            TcpTable table = ManagedIpHelper.GetExtendedTcpTable(true);
            foreach (TcpRow r in table)
            {
                if (r.ProcessId == Processes[0].Id)
                    PotentialIPs.Add(r.RemoteEndPoint);
            }

            if (PotentialIPs.Count == 0)
            {
                System.Windows.Forms.MessageBox.Show("Mabinogi has not yet connected to any servers. Are you logged in?");
                return null;
            }

            foreach (IPEndPoint ip in PotentialIPs)
            {
                Dictionary<string, Dictionary<string, int>> ret = GetFromServer(ip.Address.ToString() + "_" + ip.Port, townName);
                if (ret != null)
                    return ret;
            }
            System.Windows.Forms.MessageBox.Show("Huh. It appears we can't determine which server you're on. Try setting it manually.");
            return null;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="serverName"></param>
        /// <param name="townName"></param>
        /// <param name="profits"></param>
        public static bool PostToServer(string serverName, string townName, Dictionary<string, Dictionary<string, int>> profits)
        {
            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(Properties.Settings.Default.serverURL + string.Format("upload/{0}/{1}/json/", serverName, townName));
            req.Method = "POST";
            req.ContentType = "text/plain";
            req.UserAgent = "Mozilla/5.0 (Windows; U; MSIE 9.0; WIndows NT 9.0; en-US))";
            using (System.IO.StreamWriter w = new System.IO.StreamWriter(req.GetRequestStream()))
            {
                w.Write(json.Serialize(profits));
            }
            HttpWebResponse resp = null;
            try
            {
                resp = (HttpWebResponse)req.GetResponse();
            }
            catch (WebException ex)
            {
                if (ex.Status != WebExceptionStatus.ProtocolError)
                {
                    //System.Windows.Forms.MessageBox.Show(ex.Status.ToString());
                    return false;
                }
                resp = (HttpWebResponse)ex.Response; //Because @#$% logic.
            }
            string respStr;
            using (System.IO.StreamReader r = new System.IO.StreamReader(resp.GetResponseStream()))
            {
                respStr = r.ReadToEnd();
            }
            if (resp.StatusCode == HttpStatusCode.Conflict)
            {
                //System.Windows.Forms.MessageBox.Show(respStr);
            }
            else if (resp.StatusCode != HttpStatusCode.OK)
            {
                //System.Windows.Forms.MessageBox.Show((int)resp.StatusCode + " - " + resp.StatusDescription);
            }
            else
            {
                return true;
            }
            return false;
        }

        public static void PostToIP(string townName, Dictionary<string, Dictionary<string, int>> profits)
        {
            List<System.Diagnostics.Process> Processes = System.Diagnostics.Process.GetProcessesByName("client").ToList();
            Processes = Processes.Where(new Func<System.Diagnostics.Process, bool>((p) => { return p.MainWindowTitle.Equals("Mabinogi"); })).ToList();
            if (Processes.Count == 0)
            {
                System.Windows.Forms.MessageBox.Show("Cannot find Mabinogi! Is it running?");
                return;
            }

            List<IPEndPoint> PotentialIPs = new List<IPEndPoint>();

            TcpTable table = ManagedIpHelper.GetExtendedTcpTable(true);
            foreach (TcpRow r in table)
            {
                if (r.ProcessId == Processes[0].Id)
                    PotentialIPs.Add(r.RemoteEndPoint);
            }

            if (PotentialIPs.Count == 0)
            {
                System.Windows.Forms.MessageBox.Show("Mabinogi has not yet connected to any servers. Are you logged in?");
                return;
            }

            foreach (IPEndPoint ip in PotentialIPs)
            {
                if (PostToServer(ip.Address.ToString() + "_" + ip.Port, townName, profits))
                    return;
            }
            System.Windows.Forms.MessageBox.Show("Huh. It appears we can't determine which server you're on. Try setting it manually.");
        }
    }
}
